#include "TcpServer.hpp"
#include "Http.hpp"

using namespace std;

void Usage(const string &proc)
{
    cout << "Usage:\n\t" << proc << " serverport" << endl;
}

shared_ptr<HttpResponse> Login(shared_ptr<HttpRequest> req)
{
    string usrdata; // 保存用户提交的参数
    if (req->Method() == "GET")
    {
        usrdata = req->Args();
    }
    else if (req->Method() == "POST")
    {
        usrdata = req->Text();
    }
    else
    {
        //...
    }
    LOG(DEBUG, "Enter Login Module, usrdata:%s", usrdata.c_str());
    // 成功获取用户输入的参数
    // 处理用户输入数据
    // 1.创建管道文件
    // 2.fork()创建子进程
    // 3.子进程执行程序替换exec交由php/java进行业务处理
    // 4.程序处理结果重定向到管道的读端
    // 处理数据结束
    shared_ptr<HttpResponse> response = Factory::BuildResponse();
    response->AddStatusLine(200, "OK");
    response->AddHeader("Content-Type", "text/html");

    string resp = "<html><body><h1>Handler Data Done!</h1></body></html>";
    response->AddText(resp);
    return response;
}

//./httpserver 8888
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }
    uint16_t port = stoi(argv[1]);

    HttpServer httpsvr;

    // void AddHandler(const string pathname, func_t func)
    // wwwroot/login
    httpsvr.AddHandler("/login", Login); //此模块负责动态数据的处理

    TcpServer tcpsvr(port, std::bind(&HttpServer::HandlerHttpRequest, &httpsvr, std::placeholders::_1));

    tcpsvr.Start();

    return 0;
}